package cn.kgc.vue.aspects;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.kgc.vue.annotatios.LogOperation;
import cn.kgc.vue.entity.LogInfo;
import cn.kgc.vue.service.LogInfoService;
import cn.kgc.vue.utils.IpUtil;
import cn.kgc.vue.utils.JWTUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author 课工场
 * @date 2024/5/20
 * @description  日之通知类
 */
@Component
@Aspect
public class LogAspect {

    @Resource
    private LogInfoService logsService;

    @Resource
    private JWTUtil jwtUtil;

    @Pointcut("@annotation(cn.kgc.vue.annotatios.LogOperation)")
    public void  point(){};

    // 环绕通知  实现操作日志的记录
    @Around("point()")
    public Object  aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {


        //  方法的耗时
        Long start = System.currentTimeMillis();
        Object proceed = joinPoint.proceed();
        Long end = System.currentTimeMillis();
        Long timeConsuming = end - start;

        // 方法参数  params
        Object[] args = joinPoint.getArgs();
        String params = "";
        if (ObjectUtil.isNotEmpty(args)){
            params = JSONUtil.toJsonStr(args);
        }

        // 操作类型   模块    Method
        MethodSignature  signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        LogOperation annotation = method.getAnnotation(LogOperation.class);
        String model = annotation.model();
        String operationType = annotation.operation().getOperationType();



        //  username    url   ip   ->  request
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();


        String authorization = request.getHeader("authorization");
        String username = (String) jwtUtil.getClaims(authorization).get("username");

        String uri = request.getRequestURI();
        String ip = IpUtil.getIp(request);

        LogInfo logInfo = new LogInfo();
        logInfo.setIp(ip);
        logInfo.setDescription(operationType);
        logInfo.setModel(model);
        logInfo.setTimeConsuming(Math.toIntExact(timeConsuming));
        logInfo.setUrl(uri);
        logInfo.setUsername(username);
        logInfo.setParams(params);
        logsService.save(logInfo);

        return proceed;
    }


}
